package com.chongdong.service;

import com.alibaba.fastjson.JSON;
import com.chongdong.dao.local.mapper.*;
import com.chongdong.dao.saas.mapper.*;
import com.chongdong.entity.local.*;
import com.chongdong.entity.saas.*;
import com.chongdong.util.NameUtils;
import com.github.pagehelper.PageHelper;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SaasServiceImpl {
    @Autowired
    private SaaSSysProviderMapper saasSysProviderMapper;
    @Autowired
    private SaaSPrdBaseMapper saasPrdBaseMapper;
    @Autowired
    private SaaSPrdBrandMapper saasPrdBrandMapper;
    @Autowired
    private SaaSPrdCategoryMapper saasPrdCategoryMapper;
    @Autowired
    private SaaSPrdDetailMapper saasPrdDetailMapper;
    @Autowired
    private SaaSPrdImagesMapper saasPrdImagesMapper;
    @Autowired
    private SaaSPrdBrandProvMapper saasPrdBrandProvMapper;

    @Autowired
    private LocalPrdBrandMapper localPrdBrandMapper;
    @Autowired
    private LocalSysProviderMapper localSysProviderMapper;
    @Autowired
    private LcoalPrdCategoryMapper localPrdCategoryMapper;
    @Autowired
    private LocalPrdBaseMapper localPrdBaseMapper;
    @Autowired
    private LocalPrdDetailMapper localPrdDetailMapper;
    @Autowired
    private LocalPrdImagesMapper localPrdImagesMapper;
    @Autowired
    private LocalPrdBrandProvMapper localPrdBrandProvMapper;
    private final static Logger logger = LoggerFactory.getLogger(SaasServiceImpl.class);


    /**
     * 合并商家品牌资质信息
     */
    public void transferSysProviderAndBrandRelation() {
        saasPrdBrandProvMapper.selectAll().forEach(pb -> {
            Long saasBrandId = pb.getBrandId();
            Long saasPrvId = pb.getPrvId();
            Long localBrandId = localPrdBrandMapper.getLocalIdBySaasId(saasBrandId);
            Long localPrvId = localSysProviderMapper.getLocalIdFromSaasSysProvider(saasPrvId);
            List<LocalPrdBrandProv> select = localPrdBrandProvMapper.select(new LocalPrdBrandProv(localBrandId, localPrvId));
            if (select.size() < 1) {
                LocalPrdBrandProv localPrdBrandProv = new LocalPrdBrandProv();
                try {
                    BeanUtils.copyProperties(localBrandId, pb);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                localPrdBrandProv.setBrandId(localBrandId);
                localPrdBrandProv.setPrvId(localPrvId);
                localPrdBrandProv.setId(null);
                localPrdBrandProvMapper.insertSelective(localPrdBrandProv);
                localPrdBrandProvMapper.saveMapping(localPrdBrandProv.getId(), pb.getId());
            } else {
                localPrdBrandProvMapper.saveMapping(select.get(0).getId(), pb.getId());
            }
        });

    }

    /**
     * 更新商品图片信息
     */
    public void transferPrdImageSaaSData2SaaSPlatform(Integer pageNum, Integer pageSize) {
        pageNum = (pageNum == null ? 1 : pageNum);
        pageSize = (pageSize == null ? 5000 : pageSize);
        while (pageSize > 0) {
            PageHelper.startPage(1, pageSize);
            List<PrdImages> prdImages = saasPrdImagesMapper.selectAll();
            prdImages.forEach(i -> {
                //获取合并后的商品id
                Long prdId = localPrdDetailMapper.getLocalIdBySaasIdFromSaasPrdBase(i.getPrdId());
                List<LocalPrdImages> select =
                        localPrdImagesMapper.select(new LocalPrdImages(prdId));
                if (select.size() < 1) {
                    LocalPrdImages localPrdImages = new LocalPrdImages();
                    try {
                        BeanUtils.copyProperties(localPrdImages, i);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    localPrdImages.setId(null);
                    localPrdImages.setPrdId(prdId);
                    localPrdImagesMapper.insertSelective(localPrdImages);
                    localPrdImagesMapper.saveMapping(localPrdImages.getId(), i.getId());
                } else {
                    //以前的为主
                    localPrdImagesMapper.saveMapping(select.get(0).getId(), i.getId());
                }
            });
            pageNum++;
            pageSize = prdImages.size() == pageSize ? prdImages.size() : -1;
        }

    }

    /**
     * 更新商品详情数据
     */
    public void transferPrdDetailSaaSData2SaaSPlatform(Integer pageNum, Integer pageSize) {
        pageNum = (pageNum == null ? 1 : pageNum);
        pageSize = (pageSize == null ? 5000 : pageSize);
        Map<Long, Long> categoryMap = localPrdCategoryMapper.selectAllMapping().stream().collect(Collectors.toMap(Mapping::getOldSaasId, Mapping::getNewLocalId));
        Map<Long, Long> brandMap = localPrdBrandMapper.selectAllMapping().stream().collect(Collectors.toMap(Mapping::getOldSaasId, Mapping::getNewLocalId));

        while (pageSize > 0) {
            //根据saas_prd_base表找到对应的商品id,对应字段为local_id
            PageHelper.startPage(1, pageSize);
            List<PrdDetail> prdDetails = saasPrdDetailMapper.selectAll();
            prdDetails.forEach(d -> {
                //获取合并后的商品id
                Long proId = localPrdDetailMapper.getLocalIdBySaasIdFromSaasPrdBase(d.getPrdId());
                //获取合并后的商家id
                Long prvId = d.getPrvId();

                List<LocalPrdDetail> select = localPrdDetailMapper.select(new LocalPrdDetail(proId, prvId, d.getCode()));
                if (select.size() < 1) {
                    LocalPrdDetail localPrdDetail = new LocalPrdDetail();
                    try {
                        BeanUtils.copyProperties(localPrdDetail, d);
                    } catch (IllegalAccessException e) {
                        logger.error("当前执行的模块为合并原来的saas商品详情,错误数据为" + JSON.toJSONString(d));
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        logger.error("当前执行的模块为合并原来的saas商品详情,错误数据为" + JSON.toJSONString(d));
                        e.printStackTrace();
                    }
                    localPrdDetail.setPrvId(prvId);
                    localPrdDetail.setPrdId(proId);
                    localPrdDetail.setId(null);
                    localPrdDetailMapper.insertSelective(localPrdDetail);
                    localPrdDetailMapper.saveMapping(localPrdDetail.getId(), d.getId());
                } else {
                    localPrdDetailMapper.saveMapping(select.get(0).getId(), d.getId());
                }
            });
            pageNum++;
            pageSize = prdDetails.size() == pageSize ? prdDetails.size() : -1;
        }

    }


    /**
     * saas平台并不存在saas_id这个字段看，所以根据saas信息去重的方案不可使用，要根据名字去重
     */
    public void transferProductSaaSData2SaaSPlatform(Integer pageNum, Integer pageSize) {
        pageNum = (pageNum == null ? 1 : pageNum);
        pageSize = (pageSize == null ? 5000 : pageSize);
        Map<Long, Long> categoryMap = localPrdCategoryMapper.selectAllMapping().stream().collect(Collectors.toMap(Mapping::getOldSaasId, Mapping::getNewLocalId));

        Map<Long, Long> brandMap = localPrdBrandMapper.selectAllMapping().stream().collect(Collectors.toMap(Mapping::getOldSaasId, Mapping::getNewLocalId));
        while (pageSize > 0) {
            PageHelper.startPage(1, pageSize);
            List<PrdBase> prdBases = saasPrdBaseMapper.selectAll();
            Date createTime = new Date();
            Date updateTime = new Date();
            prdBases.forEach(p -> {
                //查询商品是否存在
                List<LocalPrdBase> select = localPrdBaseMapper.select(new LocalPrdBase(p.getName(), p.getPrvId(), brandMap.get(p.getBrandId()), p.getCode()));
                if (select.size() < 1) {
                    p.setBrandId(brandMap.get(p.getBrandId()));
                    p.setPrvId(p.getPrvId());
                    String name = null;
                    String name1 = saasPrdCategoryMapper.selectByPrimaryKey(p.getCategoryId()).getName();
                    if ("办公设备".equals(name1)) {
                        name = "其它办公设备";
                    } else if ("办公文具".equals(name1)) {
                        name = "书写工具";
                    } else if ("办公耗材".equals(name1)) {
                        name = "其它办公文具耗材";
                    } else if ("其它实验室办公用品".equals(name1)) {
                        name = "其它办公用品";
                    } else {
                        name = name1;
                    }
                    p.setCategoryId(localPrdCategoryMapper.selectOne(
                            new LocalPrdCategory(name, (byte) 3)
                    ).getId());
                    LocalPrdBase localPrdBase = copySaaSPrdBaseValue(p, createTime, updateTime);

                    localPrdBaseMapper.insertSelective(localPrdBase);
                    localPrdBaseMapper.saveMapping(localPrdBase.getId(), p.getId());
                } else {
                    localPrdBaseMapper.saveMapping(select.get(0).getId(), p.getId());
                }
            });
            logger.info("当前执行的模块为saas商品数据合并，已结束的页码为" + pageNum);
            pageNum++;
            pageSize = prdBases.size() == pageSize ? prdBases.size() : -1;
        }

    }

    /**
     * 类目以华理的为主，后期做定向更新
     */
    public void transferCategoryData2Platform() {
        saasPrdCategoryMapper.selectAll().forEach(c -> {
                    localPrdCategoryMapper.saveMapping(localPrdCategoryMapper.selectOne(new LocalPrdCategory(c.getName(), (byte) 3)).getId(), c.getId());
                }
        );
    }

    /**
     * 合并品牌，存在的不进行保存
     */
    public void transferBrandData2SaasPlatform() {
        saasPrdBrandMapper.selectAll().forEach(b -> {
            List<LocalPrdBrand> select = localPrdBrandMapper.select(new LocalPrdBrand(NameUtils.getFinalPrdBrandName(b.getName(), NameUtils.SAAS)));
            if (select.size() < 1) {
                LocalPrdBrand brand = new LocalPrdBrand();
                try {
                    BeanUtils.copyProperties(brand, b);
                } catch (IllegalAccessException e) {
                    logger.error("当前执行的模块为合并原来saas平台品牌，错误数据为" + JSON.toJSONString(b));
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    logger.error("当前执行的模块为合并原来saas平台品牌，错误数据为" + JSON.toJSONString(b));
                    e.printStackTrace();
                }
                brand.setId(null);
                localPrdBrandMapper.insertSelective(brand);
                localPrdBrandMapper.saveMapping(brand.getId(), b.getId());
            } else {
                localPrdBrandMapper.saveMapping(select.get(0).getId(), b.getId());
            }
        });
    }

    /**
     * 合并商家信息，saas上原有的商家与现在三家本地系统合并后的商家进行再次合并
     */
    @Transactional(value = "localTransactionManager")
    public void transferProviderSaaSData2SaaSPlatform() {

        List<LocalSysProvider> sysProviders = localSysProviderMapper.selectAll();
        sysProviders.forEach(s -> {
            String finalSysProviderName = NameUtils.getFinalSysProviderName(s.getName(), NameUtils.SAAS);
            if (!finalSysProviderName.equalsIgnoreCase(s.getName())) {
                LocalSysProvider p = new LocalSysProvider();
                p.setId(s.getId());
                p.setName(finalSysProviderName);
                localSysProviderMapper.updateByPrimaryKeySelective(p);
            }
        });

    }


    /**
     * 转换对象
     *
     * @param source
     * @param createTime
     * @param updateTime
     * @return
     */
    public LocalSysProvider copySaaSProviderValue(SysProvider source, Date createTime, Date updateTime) {
        LocalSysProvider dest = new LocalSysProvider();
        dest.setName(source.getName());
        dest.setAddress(source.getAddress());
        dest.setApproveStatus(source.getStatus());
        dest.setType(source.getType());
        dest.setLogo(source.getLogo());
        dest.setCreateTime(createTime);
        dest.setContact(source.getContact());
        dest.setTelephone(source.getTelephone());
        dest.setEmail(source.getEmail());
        dest.setSysNum(source.getSysNum());
        dest.setStatus(source.getStatus());
        dest.setAreaId(source.getAreaId());
        dest.setShortName(StringUtils.isBlank(source.getShortName()) ? "" : source.getShortName());
        dest.setTaxNo(source.getTaxNo());
        dest.setLicenseUrl(source.getLicenseUrl());
        dest.setUpdateTime(updateTime);
        return dest;
    }

    public LocalPrdBase copySaaSPrdBaseValue(PrdBase source, Date createTime, Date updateTime) {
        LocalPrdBase prdBase = new LocalPrdBase();
        try {
            BeanUtils.copyProperties(prdBase, source);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        prdBase.setUpdateTime(updateTime);
        prdBase.setCreateTime(createTime);
        prdBase.setId(null);
        return prdBase;
    }
}
